// 后端API基础URL
const API_BASE_URL = 'http://localhost:3000/api';

// 存储和获取token
const setToken = (token) => localStorage.setItem('token', token);
const getToken = () => localStorage.getItem('token');
const removeToken = () => localStorage.removeItem('token');

// 存储和获取用户角色
const setUserRole = (role) => localStorage.setItem('userRole', role);
const getUserRole = () => localStorage.getItem('userRole');
const removeUserRole = () => localStorage.removeItem('userRole');

// 确保函数在全局作用域可用
console.log('开始定义registerUser函数...');
window.registerUser = async function(userData) {
  console.log('registerUser function initialized:', this);
  console.log('registerUser function is called with:', userData);
  // 根据注册页面自动设置角色参数，与其他角色注册方式保持一致
  const path = window.location.pathname;
  if (path.includes('company-register')) {
    userData.role = 'company';
  } else if (path.includes('job-seeker-register')) {
    userData.role = 'jobseeker';
  }
  try {
    const response = await fetch(`${API_BASE_URL}/auth/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userData)
    });

    const result = await response.json();

    // 检查HTTP状态，成功标志为可选（如果提供则必须为true）
    if (!response.ok || (result.success === false)) {
      throw new Error(result.message || '注册失败: ' + (response.statusText || '未知错误'));
    }

    // 保存token和角色并根据角色跳转
    console.log('完整注册响应:', result);
      if (result.token) {
      setToken(result.token);
      // 增强角色提取逻辑，支持多种后端响应结构
      // 优先从data对象提取角色信息，适配后端常见响应结构
      // 提取角色并统一转为小写处理
      // 直接使用后端返回的user.role结构
      const userRole = result.user?.role?.toLowerCase();
      console.log('提取并标准化的用户角色:', userRole);
      setUserRole(userRole);
// 注册成功后跳转到相应页面
            if (result.user.role === 'company') {
                window.location.href = 'company-dashboard.html';
            } else {
                window.location.href = 'job-seeker-dashboard.html';
            }
    } else {
      console.error('注册响应缺少token:', result);
      throw new Error('注册成功但未返回认证信息');
    }

    return result;
  } catch (error) {
    console.error('注册错误:', error.message);
    throw error;
  }
}

// 用户登录
const loginUser = async (credentials) => {
  try {
    const response = await fetch(`${API_BASE_URL}/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(credentials)
    });

    const result = await response.json();

    if (!response.ok) {
      throw new Error(result.message || '登录失败');
    }

    // 保存token和角色并根据角色跳转
    if (result.token) {
      setToken(result.token);
      setUserRole(result.user.role);
// 登录成功后跳转到相应页面
        if (result.user.role === 'admin') {
            window.location.href = 'admin-dashboard.html';
        } else if (result.user.role === 'company') {
            window.location.href = 'company-dashboard.html';
        } else {
            window.location.href = 'job-seeker-dashboard.html';
        }
    }

    return result;
  } catch (error) {
    console.error('登录错误:', error.message);
    throw error;
  }
};

// 获取当前用户信息
const getCurrentUser = async () => {
  try {
    const token = getToken();
    if (!token) {
      throw new Error('用户未登录');
    }

    const response = await fetch(`${API_BASE_URL}/auth/me`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    const result = await response.json();

    if (!response.ok) {
      throw new Error(result.message || '获取用户信息失败');
    }

    return result.data;
  } catch (error) {
    console.error('获取用户信息错误:', error.message);
    throw error;
  }
};

// 用户登出
const logoutUser = () => {
  removeToken();
  removeUserRole();
    window.location.href = 'index.html';
  };


// 检查用户是否已登录
const isLoggedIn = () => !!getToken();

// 请求拦截器封装（带token）
const fetchWithAuth = async (url, options = {}) => {
  const token = getToken();
  const headers = {
    'Content-Type': 'application/json',
    ...options.headers
  };

  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(url, {
    ...options,
    headers
  });

  const result = await response.json();

  if (!response.ok) {
    // token过期处理
    if (response.status === 401 && result.message.includes('token')) {
      logoutUser();
    }
    throw new Error(result.message || '请求失败');
  }

  return result;
};

// 路由保护中间件
function protectRoute(allowedRoles) {
  console.log('registerUser函数挂载状态:', typeof window.registerUser);
  if (!isLoggedIn()) {
    window.location.href = 'login.html';
    return false;
  }
  
  const userRole = getUserRole();
  if (allowedRoles && !allowedRoles.includes(userRole)) {
    window.location.href = 'index.html';
    return false;
  }
  
  return true;
}

// 确认脚本执行完成
console.log('auth.js脚本加载完成，registerUser状态:', typeof window.registerUser);